package com.wnhz.work.jy.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.solidfire.gson.Gson;
import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.MyMain;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.adapter.ProductAdapter;
import com.wnhz.work.jy.bean.GoodDetailsBean;
import com.wnhz.work.jy.bean.ShoppingBean;
import com.wnhz.work.jy.fragment.EvaluateFragment;
import com.wnhz.work.jy.fragment.PicTextDetailsFragment;
import com.wnhz.work.jy.fragment.ProductParameterFragment;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.image.ImageOptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.CSCustomServiceInfo;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.LocationMessage;
import io.rong.message.RichContentMessage;

/**
 * ----商品详情
 */
public class GoodDetailsMainActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "GoodDetailsMainActivity";
    private MyMain myMain;
    private TextView title;
    private RelativeLayout rl_right;
    private ImageView iv_right;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FragmentPagerAdapter mAdapter;

    private List<Fragment> list_fragment; //定义要装fragment的列表
    private List<String> list_title; //tab名称列表

    private PicTextDetailsFragment fragment1;
    private ProductParameterFragment fragment2;
    private EvaluateFragment fragment3;

    public GoodDetailsBean goodDetailsBean;
    public String goodId;

    private ImageView iv_collect;
    private TextView tv_collect;

    private ShoppingBean shopBean;
    private ArrayList<ShoppingBean> selectshopList = new ArrayList<>();

    private int kucun;

    public ImageOptions options = new ImageOptions.Builder()
            //设置加载过程中的图片
            .setLoadingDrawableId(R.mipmap.img_zhanwei)
            //设置加载失败后的图片
            .setFailureDrawableId(R.mipmap.img_zhanwei)
            //设置使用缓存
            .setUseMemCache(true)
            //设置显示圆形图片
            .setCircular(false)
            //设置支持gif
            .setIgnoreGif(false)
            .build();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good_details_main);
        goodId = getIntent().getStringExtra("goodId");
        initView();
        getData();
    }


    private void initView() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("商品详情");
        rl_right = (RelativeLayout) findViewById(R.id.btn_main_right);
        iv_right = (ImageView) findViewById(R.id.view_main_right_image);
        rl_right.setVisibility(View.VISIBLE);
        iv_right.setVisibility(View.VISIBLE);
        iv_right.setImageResource(R.mipmap.ic_gouwuche_nor);
        tabLayout = (TabLayout) findViewById(R.id.tab_details);
        viewPager = (ViewPager) findViewById(R.id.vp_details);
        iv_collect = (ImageView) findViewById(R.id.iv_collect);
        tv_collect = (TextView) findViewById(R.id.tv_collect);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.rl_service).setOnClickListener(this);
        findViewById(R.id.rl_collect).setOnClickListener(this);
        findViewById(R.id.tv_inCart).setOnClickListener(this);
        findViewById(R.id.tv_buyNow).setOnClickListener(this);
        rl_right.setOnClickListener(this);

        //初始化各fragment
        fragment1 = new PicTextDetailsFragment();
        fragment2 = new ProductParameterFragment();
        fragment3 = new EvaluateFragment();

        //将fragment装进列表中
        list_fragment = new ArrayList<>();
        list_fragment.add(fragment1);
        list_fragment.add(fragment2);
        list_fragment.add(fragment3);

        //将名称加载tab名字列表
        list_title = new ArrayList<>();
        list_title.add("图文详情");
        list_title.add("产品参数");
        list_title.add("评价");

        //设置TabLayout的模式
        tabLayout.setTabMode(TabLayout.MODE_FIXED);

        //为TabLayout添加tab名称
        tabLayout.addTab(tabLayout.newTab().setText(list_title.get(0)));
        tabLayout.addTab(tabLayout.newTab().setText(list_title.get(1)));
        tabLayout.addTab(tabLayout.newTab().setText(list_title.get(2)));

        mAdapter = new ProductAdapter(GoodDetailsMainActivity.this.getSupportFragmentManager(), list_fragment, list_title);

        //viewpager加载adapter
        viewPager.setAdapter(mAdapter);
        viewPager.setOffscreenPageLimit(3);
        //TabLayout加载viewpager
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //购物车
            case R.id.btn_main_right:
                if (MyApplication.getInstance().userBean != null) {
                    startActivity(new Intent(this, CardActivity.class));
                } else {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }
                break;

            //客服
            case R.id.rl_service:
                if (MyApplication.getInstance().userBean != null) {
//                    doConnection();
                    startActivity(new Intent(this, CustomService.class));
                } else {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }
                break;

            //收藏
            case R.id.rl_collect:
                if (MyApplication.getInstance().userBean != null) {
                    if ("0".equals(goodDetailsBean.getIs_collection())) {
                        addCollectio();
                    } else {
                        cancelCollection(goodId);
                    }
                } else {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }

                break;

            //加入购物车
            case R.id.tv_inCart:
                kucun = Integer.parseInt(goodDetailsBean.getStoreNum());
                if (MyApplication.getInstance().userBean != null) {
                    if (kucun == 0) {
                        MyToast("库存为零，无法加入购物车");
                    } else {
                        addCart();
                    }
                } else {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }
                break;

            //立即购买
            case R.id.tv_buyNow:
                if (goodDetailsBean != null){
                    kucun = Integer.parseInt(goodDetailsBean.getStoreNum());
                    if (MyApplication.getInstance().userBean != null) {
                        if (kucun == 0) {
                            MyToast("库存为零，无法购买");
                        } else {
                            shopBean = new ShoppingBean();
                            shopBean.setGoodId(goodDetailsBean.getGoodId());
                            shopBean.setGoodImg(goodDetailsBean.getGoodImg());
                            shopBean.setGoodName(goodDetailsBean.getGoodName());
                            shopBean.setGoodPrice(goodDetailsBean.getGoodPrice());
                            selectshopList.add(shopBean);
                            intent = new Intent(this, GoodChooseNumberActivity.class);
                            intent.putExtra("list", selectshopList);
                            intent.putExtra("pic", goodDetailsBean.getGoodImg());
                            intent.putExtra("name", goodDetailsBean.getGoodName());
                            intent.putExtra("price", goodDetailsBean.getGoodPrice());
                            intent.putExtra("inventory", goodDetailsBean.getStoreNum());
                            startActivity(intent);
                        }
                    } else {
                        intent = new Intent(this, LoginActivity.class);
                        startActivity(intent);
                    }
                }


                break;

            default:
                break;
        }
    }

    private String token = "12CnX8azdO+/uOMydEf5/++fbYqTT4Egv7bV4d7XPX/tNG69WIpVPCKuRE62YzOhbVmH3UyS4fM=";

    private String kefu_id = "KEFU147617572444396";

    /**
     * update--2016.5.26--荣云联系客服
     */
    private void doConnection() {


        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            @Override
            public void onSuccess(String arg0) {


                if (null != RongIM.getInstance()) {


                    // 联系客服
                    //RongIM.getInstance().startCustomerServiceChat(ContactActivity.this, kefu_id, "在线客服");

                    //首先需要构造使用客服者的用户信息
                    CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
                    CSCustomServiceInfo csInfo = csBuilder.nickName("融云").build();
                    Toast.makeText(GoodDetailsMainActivity.this, "客服", Toast.LENGTH_SHORT).show();
                    RongIM.getInstance().startCustomerServiceChat(GoodDetailsMainActivity.this, kefu_id, "在线客服", csInfo);

                    // 修改用户信息
                } else {

                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode arg0) {


            }

            @Override
            public void onTokenIncorrect() {

            }
        });

        RongIM.setConversationBehaviorListener(new RongIM.ConversationBehaviorListener() {


            @Override
            public boolean onMessageLongClick(Context arg0, View arg1, Message arg2) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onMessageLinkClick(Context arg0, String arg1) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, io.rong.imlib.model.UserInfo userInfo) {
                return false;
            }

            @Override
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, io.rong.imlib.model.UserInfo userInfo) {
                return false;
            }

            @Override
            public boolean onMessageClick(Context context, View view, Message message) {
                // 点击消息处理事件，示例代码展示了如何获得消息内容
                if (message.getContent() instanceof LocationMessage) {
                    // Intent intent = new Intent(context,
                    // LocationActivity.class);
                    // intent.putExtra("location", message.getContent());
                    // context.startActivity(intent);

                } else if (message.getContent() instanceof RichContentMessage) {
                    RichContentMessage mRichContentMessage = (RichContentMessage) message.getContent();

                }


                return false;
            }
        });
    }

    public void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("goodId", goodId);
        if (MyApplication.getInstance().userBean != null) {
            map.put("userId", MyApplication.getInstance().userBean.getUserId());
        }
        showDialog();
        XUtil.Post(ConfigUtil.GOODS_DETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: " + result);
                goodDetailsBean = new Gson().fromJson(result, GoodDetailsBean.class);
                System.out.println(goodDetailsBean.toString());
                fragment1.setData();
                fragment1.initWeb(goodDetailsBean.getDescribeImgs());
                fragment2.setData();
                isCollect();
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

    private void isCollect() {

        if ("0".equals(goodDetailsBean.getIs_collection())) {
            iv_collect.setImageResource(R.mipmap.ic_shoucang);
            tv_collect.setText("收藏");
        } else if ("1".equals(goodDetailsBean.getIs_collection())) {
            iv_collect.setImageResource(R.mipmap.ic_shoucang_li);
            tv_collect.setText("已收藏");
        }
    }

    private void addCart() {
        Map<String, Object> map = new HashMap<>();
        map.put("goodId", goodId);
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        XUtil.Post(ConfigUtil.ADD_CART, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: " + result);
                try {
                    JSONObject object = new JSONObject(result);
                    String info = object.optString("info");
                    Toast.makeText(getApplication(), info, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Log.e(TAG, "onError: e" + ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                super.onCancelled(cex);
                Log.e(TAG, "onCancelled: c" + cex);
            }
        });
    }

    private void addCollectio() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        map.put("goodId", goodId);
        XUtil.Post(ConfigUtil.ADDTO_MY_COLLECTION, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: c " + result);
                try {
                    JSONObject jsonobject = new JSONObject(result);
                    String re = jsonobject.optString("result");
                    if ("1".equals(re)) {

                        if ("0".equals(goodDetailsBean.getIs_collection())) {
                            goodDetailsBean.setIs_collection("1");
                        }
                        isCollect();
                    }
                    String info = jsonobject.optString("info");
                    Toast.makeText(getApplication(), info, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void cancelCollection(String goodId) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        map.put("goodId", goodId);
        showDialog();
        XUtil.Post(ConfigUtil.CANCEL_MY_COLLECTION, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject js = new JSONObject(result);
                    String re = js.optString("result");
                    String info = js.optString("info");
                    if ("1".equals(re)) {
                        if ("1".equals(goodDetailsBean.getIs_collection())) {
                            goodDetailsBean.setIs_collection("0");
                        }
                        isCollect();
                    }
                    Toast.makeText(getApplication(), info, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }
}
